import { useState, useEffect } from "react";
import { Button, Modal, Form, Input, InputNumber } from "antd";
import { useStore } from "@/store";
import { nanoid } from "nanoid";

const CodeModal = ({ visibleCodeModal, isAdd, elementsIndex }) => {
  const [modalVisible, setModalVisible] = useState(false);
  const [form] = Form.useForm();
  const { slideList, currentSlideIndex, setCurrentPresentation, updateSlide } =
    useStore();

  useEffect(() => {
    if (visibleCodeModal) {
      setModalVisible(true);

      if (isAdd) {
        form.resetFields();
      } else {
        // 编辑进来
        const { blockWidth, blockHeight, content, fontSize } =
          slideList[currentSlideIndex - 1].elements[elementsIndex];
        form.setFieldsValue({
          blockWidth,
          blockHeight,
          content,
          fontSize,
        });
      }
    }
  }, [visibleCodeModal]);

  const handleCancel = () => {
    form.resetFields();
    setModalVisible(false);
  };

  const handleOK = () => {
    form.validateFields().then((values) => {
      const newSlideList = [...slideList];
      if (isAdd) {
        // 新增一个元素
        newSlideList[currentSlideIndex - 1].elements.push({
          sortId: newSlideList[currentSlideIndex - 1].elements.length + 1, // 排序id
          id: nanoid(),
          type: "Code",
          ...values,
        });
      } else {
        // 修改一个元素
        newSlideList[currentSlideIndex - 1].elements[elementsIndex] = {
          ...newSlideList[currentSlideIndex - 1].elements[elementsIndex],
          ...values,
        };
      }
      //  修改一个元素时
      updateSlide(newSlideList);
      setModalVisible(false);
    });
  };

  return (
    <Modal
      title={"设置代码"}
      open={modalVisible}
      onCancel={handleCancel}
      onOk={handleOK}
      okText="确定"
      cancelText="取消"
    >
      <Form
        labelCol={{ span: 6 }}
        form={form}
        initialValues={{
          blockWidth: 500,
          blockHeight: 250,
          content: "",
          fontSize: 1,
        }}
      >
        <Form.Item
          label="代码块宽度"
          name="blockWidth"
          rules={[{ required: true, message: "不得为空" }]}
        >
          <InputNumber style={{ width: "100%" }} />
        </Form.Item>
        <Form.Item
          label="代码块高度"
          name="blockHeight"
          rules={[{ required: true, message: "不得为空" }]}
        >
          <InputNumber style={{ width: "100%" }} />
        </Form.Item>
        <Form.Item
          label="代码内容"
          name="content"
          rules={[{ required: true, message: "不得为空" }]}
        >
          <Input.TextArea rows={4} />
        </Form.Item>
        <Form.Item
          label="代码字体大小"
          name="fontSize"
          rules={[{ required: true, message: "不得为空" }]}
        >
          <InputNumber style={{ width: "100%" }} />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default CodeModal;
